package com.ksd.dao.impl;

import com.ksd.dao.IAddressDAO;
import com.ksd.pojo.Address;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public class AddressDAO implements IAddressDAO {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * get address list
     */
    public List findAllByUsername(final String username) {
        return sessionFactory.getCurrentSession().createCriteria(Address.class).add(
                Restrictions.eq("username", username)).list();
    }

    @Transactional
    public Address findById(String id) {
        return (Address) sessionFactory.getCurrentSession().createCriteria(Address.class).add(
                Restrictions.eq("id", new Integer(id))).list();
    }

    public boolean isExist(final String username, final String name) {
        List list = sessionFactory.getCurrentSession().createCriteria(Address.class)
                .add(Restrictions.eq("username", username))
                .add(Restrictions.eq("name", name)).list();
        return list.size() > 0;
    }

    public void insert(Address address) {
        sessionFactory.getCurrentSession().save(address);
    }

    public void update(Address address) {
        sessionFactory.getCurrentSession().update(address);
    }

    public void delete(String id) {
        Object p = sessionFactory.getCurrentSession().load(Address.class, new Integer(id));
        sessionFactory.getCurrentSession().delete(p);
    }
}
